<template>
	<div class="system-role-container layout-padding">
		<div class="system-role-padding layout-padding-auto">
			<div class="form-designer-box">
				<v-form-designer :form-json="state.formJson" :form-data="state.formData" :designer-config="state.designerConfig" @importCascaderOptionsOpen="importCascaderOptionsOpen" ref="vfdRef">
					<template #customToolButtons>
						<div class="custom-toolbar-buttons font16">
							<el-button link type="primary" @click="saveForm()">保存</el-button>
						</div>
					</template>
				</v-form-designer>
				<el-dialog v-model="state.visible" title="级联选项设置" width="600">
					<el-alert show-icon :closable="false" title="删除选项时，因将value作为id使用，在编辑时请确保value值的唯一性" type="info" />
					<el-scrollbar height="400px">
						<el-tree :data="state.optionData" @node-click="handleNodeClick" :key="state.cascaderKey"
							draggable :props="state.optionProps">
							<template #default="{ node, data }">
								<div class="ex-property-col">
									<div class="flex flex-column-center">
										<el-input class=" ml10 mt10" v-model="data[state.optionProps.label]">
											<template #prepend>选项名</template>
										</el-input>
										<el-input class=" ml10 mt10" v-model="data[state.optionProps.value]"><template
												#prepend>选项值</template></el-input>
										<el-input class=" ml10 mt10" v-model="data[state.optionProps.url]"><template
												#prepend>跳转链接</template>
											<template #append>
												<span class="cursor-pointer" @click.stop="addUlr(node,data)">选择</span>
											</template></el-input>
									</div>
									<div class="flex flex-column-center">
										<span>选择图片</span>
										<div class="upLoadPicBox ml10">
											<div class="item addItem" style="width:80px;height: 80px;"
												@click.stop="addImg(node,data)" v-if="!data[state.optionProps.imgUrl]">
												<el-icon><ele-Plus /></el-icon>
											</div>
											<div class="item" style="width:80px;height: 80px;" v-else>
												<img :src="data[state.optionProps.imgUrl]"
													style="width:80px;height: 80px;" />
												<div class="image-preview-action">
													<el-icon><ele-Delete
															@click="data[state.optionProps.imgUrl] = ''" /></el-icon>
												</div>
											</div>
										</div>
									</div>
									<el-button @click.stop="handleAddChild(data)" class="ml10 width30" icon="ele-Plus"
										type="primary" plain circle />
									<el-button @click.stop="handleDel(node, data)" class="ml10 width30" icon="ele-Minus"
										type="danger" plain circle />
								</div>
							</template>
						</el-tree>
					</el-scrollbar>
					<template #footer>
						<span>
							<el-button @click="handleAdd" size="default" type="primary">
								添加选项
							</el-button>
							<el-button @click="state.visible = false" size="default">确定</el-button>
						</span>
					</template>
				</el-dialog>
				<AddInformation ref="addInformationRef" @selectFun="selectFun" />
				<LinkAddress ref="linkAddressRef" @linkUrl="linkUrl"></LinkAddress>
			</div>
		</div>
	</div>

</template>

<script setup lang="ts">
	type TreeData = { [key : string] : any };
	import { ElMessage } from "element-plus";
	import { useRoute } from 'vue-router';
	import { reactive, ref, onMounted, computed, defineAsyncComponent } from "vue";
	import { useFormDesignerApi } from '/@/api/formDesigner/index'
	import type Node from "element-plus/es/components/tree/src/model/node";
	const AddInformation = defineAsyncComponent(() => import('/@/components/information/AddInformation.vue'))//素材管理
	const addInformationRef = ref()
	const LinkAddress = defineAsyncComponent(() => import('/@/components/linkAddress/index.vue')) //地址选择组件
	const linkAddressRef = ref()
	const route = useRoute();
	const formDesignerApi = useFormDesignerApi() //表单api
	const state = reactive({
		designerConfig: {
			logoHeader: false, //是否显示顶部LOGO条（仅Pro） 找的别人的pro版本代码
			importJsonButton: false,//是否显示导入JSON按钮
			exportJsonButton: true,//是否显示导出JSON按钮
			generateSFCButton: false,//是否显示生成SFC按钮
			exportCodeButton: false,//是否显示导出代码按钮
			formTemplates: false,//是否显示表单模板
			eventCollapse: false,//是否显示组件事件属性折叠面板
			toolbarMaxWidth: 800,
		},
		nameInput: "", //模版输入的名称
		id: <any>'',//自定义表单ID
		nameVisible: false, //修改名字气泡状态
		visible: false,//自定义配置弹框
		formJson: {},
		optionData: <EmptyObjectType>{},//所选中的级联选择器配置数据
		optionProps: <any>{}, //所选中的级联选择器配置
		cascaderKey: <any>'',
		nodeClickData: <any>{}
	})
	const vfdRef = ref()
	const saveFormName = () => {

	};//保存模版名称

	const saveForm = () => {
		let formJson = vfdRef.value.getFormJson()
		let params = {
			ProjectID: route.query.projectID,
			RouteID: route.query.RouteID,
			PageData: JSON.stringify(formJson)
		}
		formDesignerApi.upsert(params).then(res => {
			ElMessage.success("保存成功")
			router.go(-1)
		})
	}
	const importCascaderOptionsOpen = (res : any) => {
		console.log(res)
		state.optionData = res.optionItems
		state.optionProps = {
			label: res.labelKey,
			value: res.valueKey,
			children: res.childrenKey,
			url: 'url', //跳转链接
			imgUrl: 'imgUrl',//图片链接
		}

		state.cascaderKey = res.name
		state.visible = true
	}
	const settingOptions = computed({
		get: () => state.optionData,
		set: (val) => val
	});
	const handleNodeClick = () => {
		// console.log(settingOptions.value);
	};
	const getOptions = (value : string | number) => {
		let item : TreeData = {};
		item[state.optionProps.label] = "new option";
		item[state.optionProps.value] = value;
		item[state.optionProps.children] = [];
		item[state.optionProps.url] = "";
		item[state.optionProps.imgUrl] = "";
		return item;
	};

	const handleAddChild = (data : TreeData) => {
		if (!data[state.optionProps.children]) data[state.optionProps.children] = [];
		let children = data[state.optionProps.children];
		let value = data[state.optionProps.value];
		let len = children.length + 1;
		let text = value + "-" + len;
		console.log(text)

		children.push(getOptions(text));
	};

	const handleAdd = () => {
		let len = settingOptions.value.length + 1;
		console.log(settingOptions)

		settingOptions.value.push(getOptions(len));
	};

	const handleDel = (node : Node, data : TreeData) => {
		const parent = node.parent;
		let parentChildren = parent.data[state.optionProps.children] as TreeData[];
		const children = parentChildren || parent.data;
		const index = children.findIndex((d) => d.value === data.value);
		// if (data.children?.length > 0) {
		// 	ElMessage.error("该节点还存在子节点，无法删除");
		// 	return;
		// }
		// children.splice(index, 1);
	};
	const getRouteId = () => {
		let params = {
			RouteID: route.query.RouteID,
		}
		state.formJson = {};
		formDesignerApi.detial(params).then(res => {
			if (res.data.Data != null) {
				state.formJson = JSON.parse(res.data.Data.PageData)
				vfdRef.value.setFormJson(state.formJson)
			} else {
				vfdRef.value.clearDesigner()
			}
		})
		// let id = route.query.id
		// if (id) {
		//   let paramsData = <any>route.query
		//   state.id = id
		//   state.formJson = paramsData?.formData
		//   vfdRef.value.setFormJson(state.formJson)
		// } else {
		//   vfdRef.value.clearDesigner()
		// }
	}; //获取路由ID
	// 链接选中回调
	const linkUrl = (url : any) => {
		console.log(url)

		state.nodeClickData[0].url = url
		console.log(state.nodeClickData)

	};
	// 图片选中回调
	const selectFun = (fileList : any) => {
		state.nodeClickData[0].imgUrl = fileList[0]
	};
	// 图片选中
	const addImg = (node : Node, data : TreeData) => {
		const parent = node.parent;
		let parentChildren = parent.data[state.optionProps.children] as TreeData[];
		const children = parentChildren || parent.data;
		state.nodeClickData = children
		addInformationRef.value.openDialog(0)
	};
	const addUlr = (node : Node, data : TreeData) => {
		const parent = node.parent;
		let parentChildren = parent.data[state.optionProps.children] as TreeData[];
		const children = parentChildren || parent.data;
		state.nodeClickData = children
		console.log(state.nodeClickData)

		linkAddressRef.value.openDialog()
	};
	onMounted(() => {
		getRouteId()
	})
</script>

<style lang="scss">
	.upLoadPicBox {
		display: flex;
		justify-content: flex-start;

		.item {
			width: 80px;
			height: 80px;
			position: relative;

			img {
				width: 80px;
				height: 80px;
			}

			.image-preview-action {
				position: absolute;
				width: 100%;
				height: 100%;
				left: 0;
				top: 0;
				cursor: default;
				text-align: center;
				color: #fff;
				opacity: 0;
				font-size: 14px;
				background-color: rgba(0, 0, 0, .5);
				transition: opacity .3s;
				cursor: pointer;
				text-align: center;
				line-height: 80px;

				.el-icon-delete {
					font-size: 14px;
				}
			}

			&:hover {
				.image-preview-action {
					opacity: 1;
				}
			}
		}

		.addItem {
			border: 1px solid #E2E2E2;
			border-radius: 5px;
			display: flex;
			align-items: center;
			justify-content: center;
		}


	}

	.form-designer-box {

		.custom-toolbar-buttons {
			display: inline-block;
			margin-left: 10px
		}

		.el-tree-node__content {
			height: auto;
			padding: 3px 0;
		}



		.ex-property-col {
			display: flex;
			align-items: center;
			list-style: none;
			text-decoration: none;
		}

		.ex-property-col_title {
			display: inline-block;
			width: 130px;
			font-size: 13px;
		}


	}
</style>